<template>
    <div>
        <div>
            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     label-position="left" size="small">
                <el-row>
                    <el-col>
                        <el-form-item>
                            <el-button type="success" v-on:click="showConfigDialog">配置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="danger" v-on:click="onDelete(pushConfig)">删除配置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="warning" v-on:click="onSubscribe(pushConfig)">订阅消息</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <el-descriptions title="" direction="vertical" :column="4" border size="small" v-if="mode === 'single'">
            <el-descriptions-item label="推送公众号">
                {{ pushConfig.appName }}
            </el-descriptions-item>
            <el-descriptions-item label="推送公众号APP_ID">
                {{ pushConfig.appId }}
            </el-descriptions-item>
            <el-descriptions-item label="用户OPEN_ID">
                {{ pushConfig.openIds }}
            </el-descriptions-item>
            <el-descriptions-item label="用户手机号">
                {{ pushConfig.mobileNos }}
            </el-descriptions-item>
            <el-descriptions-item label="关联小程序">
                {{ pushConfig.mnpAppName }}
            </el-descriptions-item>
            <el-descriptions-item label="关联小程序APP_ID">
                {{ pushConfig.mnpAppId }}
            </el-descriptions-item>
            <el-descriptions-item label="点评数据路径">
                {{ pushConfig.dataPagePath }}
            </el-descriptions-item>
            <el-descriptions-item label="点评评价路径">
                {{ pushConfig.feedbackPagePath }}
            </el-descriptions-item>
            <el-descriptions-item label="好评推送开关">
                <el-switch
                    v-model="pushConfig.goodFeedbackPushFlag"
                    @change="updateSwitch()">
                </el-switch>
            </el-descriptions-item>
            <el-descriptions-item label="差评推送开关">
                <el-switch
                    v-model="pushConfig.badFeedbackPushFlag"
                    @change="updateSwitch()">
                </el-switch>
            </el-descriptions-item>
            <el-descriptions-item label="数据变化推送开关">
                <el-switch
                    v-model="pushConfig.dataChangePushFlag"
                    @change="updateSwitch()">
                </el-switch>
            </el-descriptions-item>
            <el-descriptions-item label="状态">
                <el-switch
                    v-model="pushConfig.status"
                    @change="updateSwitch()"
                    active-color="#13ce66"
                    inactive-color="#ff4949">
                </el-switch>
            </el-descriptions-item>
            <el-descriptions-item label="备注">
                {{ pushConfig.remark }}
            </el-descriptions-item>
        </el-descriptions>

        <el-table
            v-if="mode === 'table'"
            id="mainTable"
            :data="tableData"
            size="small"
            header-cell-class-name="tableHeaderStyle"
            :row-class-name="tableRowClassName">
            <el-table-column
                prop="id"
                label="唯一ID">
            </el-table-column>
            <el-table-column
                prop="shopName"
                label="门店名称">
            </el-table-column>
            <el-table-column
                prop="shopId"
                label="门店ID">
            </el-table-column>
            <el-table-column
                prop="appId"
                label="推送公众号APP_ID">
            </el-table-column>
            <el-table-column
                prop="openIds"
                label="推送OPEN_ID">
            </el-table-column>
            <el-table-column
                prop="mobileNos"
                label="推送手机号码">
            </el-table-column>
            <el-table-column
                prop="remark"
                label="备注">
            </el-table-column>
            <el-table-column
                prop="updateTime"
                label="更新时间">
            </el-table-column>
            <el-table-column
                prop="createTime"
                label="创建时间">
            </el-table-column>
            <el-table-column
                label="操作"
                fixed="right"
                width="80px">
                <template v-slot="scope">
                    <div>
                        <el-button @click="showUpdateDialog(scope.row)" type="text" size="small">编辑</el-button>
                        <el-button @click="onDelete(scope.row)" type="text" size="small">删除</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            small
            :hide-on-single-page="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="condition.page"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size.sync="condition.rows"
            layout="sizes, prev, pager, next"
            :total.sync="condition.total">
        </el-pagination>
        <el-dialog :title=addOrUpdateDialogTitle width="30%" :visible.sync="addOrUpdateDialogVisible">
            <el-form :model="addOrUpdateForm" label-width="140px" size="small">
                <el-form-item label="推送公众号">
                    <el-select v-model="addOrUpdateForm.appId" placeholder="选择公众号" style="width:200px;">
                        <el-option
                            v-for="item in officialAccounts"
                            :key="item.id"
                            :label="item.name"
                            :value="item.appId">
                            {{ item.name }}
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="推送OPEN_ID">
                    <el-input v-model="addOrUpdateForm.openIds" type="textarea" :autosize="{ minRows: 2}"
                              placeholder="推送OPEN_ID"></el-input>
                </el-form-item>
                <el-form-item label="推送手机号码">
                    <el-input v-model="addOrUpdateForm.mobileNos" type="textarea" :autosize="{ minRows: 2}"
                              placeholder="推送手机号码"></el-input>
                </el-form-item>
                <el-form-item label="关联小程序">
                    <el-select v-model="addOrUpdateForm.mnpAppId" placeholder="选择小程序" clearable
                               style="width:200px;">
                        <el-option
                            v-for="item in miniApps"
                            :key="item.id"
                            :label="item.name"
                            :value="item.appId">
                            {{ item.name }}
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="评价小程序路径">
                    <el-input v-model="addOrUpdateForm.feedbackPagePath" type="textarea" :autosize="{ minRows: 2}"
                              placeholder="请输入评价小程序路径"></el-input>
                </el-form-item>
                <el-form-item label="数据小程序路径">
                    <el-input v-model="addOrUpdateForm.dataPagePath" type="textarea" :autosize="{ minRows: 2}"
                              placeholder="请输入数据小程序路径"></el-input>
                </el-form-item>
                <el-form-item label="好评推送开关">
                    <el-switch v-model="addOrUpdateForm.goodFeedbackPushFlag"></el-switch>
                </el-form-item>
                <el-form-item label="差评推送开光">
                    <el-switch v-model="addOrUpdateForm.badFeedbackPushFlag"></el-switch>
                </el-form-item>
                <el-form-item label="数据变化推送开关">
                    <el-switch v-model="addOrUpdateForm.dataChangePushFlag"></el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addOrUpdateDialogVisible = false" size="small">取 消</el-button>
                <el-button @click="addOrUpdateConfirm" type="primary" size="small">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="订阅消息" width="40%" :visible.sync="subscribeDialogVisible">
            <el-form label-width="140px" size="small">
                <el-form-item label="订阅提醒：">
                    <div class="el-form-item__label">关注公众号{{ this.pushConfig.appName }}，输入：
                        <el-link @click="copyMsg(subscribeMsg)">{{ subscribeMsg }}</el-link>
                    </div>
                </el-form-item>
                <el-form-item label="取消订阅：">
                    <div class="el-form-item__label">关注公众号{{ this.pushConfig.appName }}，输入：
                        <el-link @click="copyMsg(unSubscribeMsg)">{{ unSubscribeMsg }}</el-link>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="subscribeDialogVisible = false" type="primary" size="small">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    addDpPushConfig,
    deleteDpPushConfig,
    getDpPushConfigByPage,
    getMpInfoByPage,
    updateDpPushConfig
} from '@/api/api'

export default {
    name: "DpPushConfig",
    data() {
        return {
            // 分页搜索条件
            condition: {
                page: 1,
                rows: 10,
                total: 0,
                search: {}
            },
            // 表格数据
            tableData: [],
            // 新增或者编辑对话框显示
            addOrUpdateDialogVisible: false,
            // 标题
            addOrUpdateDialogTitle: '新增',
            // 新增或者编辑对话框表单
            addOrUpdateForm: {},
            // 选中行
            selectedRow: {},

            mode: 'single',
            pushConfig: {},

            // 公众号列表
            officialAccounts: [],
            // 小程序列表
            miniApps: [],

            subscribeDialogVisible: false,
        }
    },
    // 这里定义需要父组件传过来的东西
    props: {
        shopId: String,
        shopName: String,
        size: {
            type: String,
            default: 'small'
        },
    },
    watch: {
        shopName: function (val, oldVal) {
            this.shopName = val;
        }
    },
    computed: {
        subscribeMsg() {
            return "订阅提醒" + this.shopName + "：" + this.shopId;
        },
        unSubscribeMsg() {
            return "取消订阅" + this.shopName + "：" + this.shopId;
        },
    },
    methods: {
        copyMsg(msg) {
            navigator.clipboard.writeText(msg).then(() => {
                this.$message({
                    type: 'success',
                    message: '复制成功!'
                });
            }).catch(err => {
                // This can happen if the user denies clipboard permissions:
                console.error('Could not copy text: ', err);
            });
        },
        // 这里可以单独设置每一行的样式
        tableRowClassName({row, rowIndex}) {
            return '';
        },
        handleSizeChange(val) {
            this.getData();
        },
        handleCurrentChange(val) {
            this.getData();
        },
        // 格式布尔值
        formatBoolean: function (row, column, cellValue) {
            if (cellValue) {
                return "是";
            } else {
                return "否";
            }
        },
        showConfigDialog: function () {
            this.addOrUpdateDialogTitle = '配置';
            this.addOrUpdateDialogVisible = true;
            this.addOrUpdateForm = {};
            // 深拷贝
            if (this.pushConfig.id) {
                this.addOrUpdateForm = Object.assign({}, this.pushConfig);
            } else {
                this.$set(this.addOrUpdateForm, "feedbackPagePath", '/pages/admin/feedback/detail/index');
                this.$set(this.addOrUpdateForm, "dataPagePath", '/pages/admin/dp/index');
                this.$set(this.addOrUpdateForm, "goodFeedbackPushFlag", false);
                this.$set(this.addOrUpdateForm, "badFeedbackPushFlag", true);
                this.$set(this.addOrUpdateForm, "dataChangePushFlag", true);
            }
            // 复制
            if (this.shopId) {
                this.addOrUpdateForm.shopId = this.shopId;
            }
            this.getOfficialAccounts();
            this.getMiniApps();
        },
        showAddDialog: function () {
            this.addOrUpdateDialogTitle = '新增';
            this.addOrUpdateDialogVisible = true;
            this.addOrUpdateForm = {};
            if (this.shopId) {
                this.addOrUpdateForm.shopId = this.shopId;
            }
        },
        showUpdateDialog: function (row) {
            this.addOrUpdateDialogTitle = '编辑';
            this.addOrUpdateDialogVisible = true;
            this.selectedRow = row;
            // 深拷贝
            this.addOrUpdateForm = Object.assign({}, row);
        },
        reset: function () {
            this.$refs['searchForm'].resetFields();
        },
        exportExcel: function () {
            this.GLOBAL.exportExcel('#mainTable', '数据.xlsx');
        },
        add: function () {
            addDpPushConfig(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        update: function () {
            updateDpPushConfig(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        config: function () {
            if (this.pushConfig.id) {
                this.update();
            } else {
                this.add();
            }
        },
        updateSwitch: function () {
            if (this.pushConfig.id) {
                updateDpPushConfig(this.pushConfig).then(data => {
                    if (data.respCode == 1000) {
                        this.getData();
                    }
                });
            } else {
                // 第一次配置
                this.$message({
                    type: 'error',
                    message: '请先完成首次配置!'
                });
            }
        },
        onSubscribe: function (row) {
            if (!row.id) {
                this.$message({
                    type: 'error',
                    message: '暂时没有配置可以删除!'
                });
                return;
            }
            this.subscribeDialogVisible = true;
        },
        onDelete: function (row) {
            if (!row.id) {
                this.$message({
                    type: 'error',
                    message: '暂时没有配置可以删除!'
                });
                return;
            }
            this.$confirm('请确认是否删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteDpPushConfig({id: row.id}).then(data => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        addOrUpdateConfirm: function () {
            if (this.addOrUpdateDialogTitle == '新增') {
                this.add();
            } else if (this.addOrUpdateDialogTitle == '编辑') {
                this.update();
            } else if (this.addOrUpdateDialogTitle == '配置') {
                this.config();
            }
        },
        // 获取表格数据
        getData: function () {
            if (this.shopId) {
                this.condition.search.shopId = this.shopId;
            }
            getDpPushConfigByPage(this.condition).then(data => {
                this.tableData = data.body.rows;
                this.condition.total = data.body.total;
                if (this.tableData.length > 0) {
                    this.pushConfig = this.tableData[0];
                } else {
                    this.pushConfig = [];
                }
            });
        },

        // 获取公众号列表
        getOfficialAccounts: function () {
            let condition = {
                page: 1,
                rows: 100,
                search: {
                    accountType: 'OFFICIAL_ACCOUNT'
                }
            };
            getMpInfoByPage(condition).then(data => {
                this.officialAccounts = data.body.rows;
            });
        },

        // 获取小程序列表
        getMiniApps: function () {
            let condition = {
                page: 1,
                rows: 100,
                search: {
                    accountType: 'MINI_PROGRAM'
                }
            };
            getMpInfoByPage(condition).then(data => {
                this.miniApps = data.body.rows;
            });
        },
    },
    created() {
        this.getData();
    },
}
</script>

<style scoped>
.el-input {
    width: 150px !important;
}

.el-select {
    width: 150px !important;
}
</style>
